<template>
  <div>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane
        v-for="item in tabList"
        :key="item.key"
        :label="item.label"
        :name="item.key"
      />
    </el-tabs>
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="商品名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <span style="margin-left: 20px" />
      <el-button
        class="filter-item"
        type=""
        icon="el-icon-search"
        @click="handleFilter"
      >
        筛选
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete">
        删除
      </el-button>
      <el-button
        class="filter-item"
        style="float: right"
        type="primary"
        icon="el-icon-edit"
        @click="handleShowGoodsForm('create')"
      >
        添加
      </el-button>
    </div>
    <br />

    <el-table
      key="goods"
      v-loading="listLoading"
      :data="goodsList"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        width="55"
        label="ID"
        align="center"
        prop="id"
      />
      <el-table-column label="商品图片" align="center">
        <template slot-scope="{ row }">
          <img width="60px" height="60px" :src="row.logo" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="left">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="总销量" align="center" prop="sales" />
      <el-table-column label="库存" align="center" prop="total" />
      <el-table-column label="是否上架" align="center">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            @change="switchChange(row)"
            name="status"
            active-value="1"
            inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleShowGoodsForm('update', row)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDeleteGoods(row)"
            />
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="80%"
      :append-to-body="true"
      @close="handleGoodsFormClose"
    >
      <el-form
        v-loading="getInfoLoading"
        ref="goodsFormRef"
        :rules="rules"
        :model="formDefaultValue"
        label-position="right"
        label-width="100px"
        style="margin-left: 30px; margin-right: 30px"
      >
        <el-tabs v-model="formTabActiveName">
          <el-tab-pane label="基本信息" name="base">
            <el-form-item label="商品分类" prop="categories">
              <el-cascader
                ref="cascaderRef"
                v-model="formDefaultValue.categories"
                placeholder="请选择商品分类"
                :options="goodCategory"
                :props="cascaderProps"
                clearable
                style="width: 100%"
                @change="getBrands"
              />
            </el-form-item>
            <el-form-item label="商品标题" prop="title">
              <el-input v-model="formDefaultValue.title" />
            </el-form-item>
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model="formDefaultValue.subtitle" />
            </el-form-item>
            <el-form-item label="品牌">
              <el-select
                v-model="formDefaultValue.brand_id"
                class="filter-item"
                placeholder="请选择品牌"
                style="width: 100%"
              >
                <el-option
                  v-for="item in goodsBrands"
                  :key="item.brand_id"
                  :label="item.name"
                  :value="item.brand_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="运费" prop="dispatch_price">
              <el-input v-model="formDefaultValue.dispatch_price" />
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                ref="upload"
                :headers="headers"
                :action="uploadUrl"
                list-type="picture-card"
                :multiple="true"
                :on-success="uploadSuccessHook"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :auto-upload="true"
                name="image"
                :file-list="goodsImages"
              >
                <i class="el-icon-plus" />
              </el-upload>
              <el-dialog :visible.sync="dialogImageVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="formDefaultValue.status">
                <el-radio label="1">上架</el-radio>
                <el-radio label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="销售价" prop="price">
              <el-input v-model="formDefaultValue.price" />
            </el-form-item>
            <el-form-item label="原价" prop="cost_price">
              <el-input v-model="formDefaultValue.cost_price" />
            </el-form-item>
            <el-form-item label="成本价" prop="original_price">
              <el-input v-model="formDefaultValue.original_price" />
            </el-form-item>
            <el-form-item label="起售量">
              <el-input-number
                v-model="formDefaultValue.min_buy"
                :min="1"
                label="起售数量"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="规格库存" name="spec">
            <el-form-item label="商品编码" prop="codes">
              <el-input v-model="formDefaultValue.codes" />
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="formDefaultValue.weight" />
            </el-form-item>
            <el-form-item label="商品库存" prop="total">
              <el-input v-model="formDefaultValue.total" />
            </el-form-item>
            <el-form-item label="规格">
              <template>
                <el-checkbox v-model="formDefaultValue.hasoption"
                  >开启商品多规格</el-checkbox
                >
                <el-button
                  v-if="formDefaultValue.hasoption == 1"
                  style="margin-left: 30px"
                  type="primary"
                  @click="addOneOption"
                  >添加规格</el-button
                >
              </template>
            </el-form-item>
            <div v-if="formDefaultValue.hasoption == 1">
              <el-form-item
                label="规格名称"
                v-if="formDefaultValue.spec_item.length > 0"
              >
                <el-input
                  v-for="(item, index) in formDefaultValue.spec_item"
                  :key="index"
                  v-model="item.name"
                  placeholder="如：颜色"
                  class="spec-option"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-delete"
                    @click="deleteSpec(index)"
                  ></i>
                </el-input>
              </el-form-item>
              <el-form-item
                :label="sitem.name"
                v-for="(sitem, sindex) in formDefaultValue.spec_item"
                :key="sindex"
              >
                <el-input
                  v-for="(iitem, iindex) in sitem.item"
                  :key="iindex"
                  v-model="iitem.title"
                  class="spec-option-item"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-delete"
                    @click="deleteSpecItem(sindex, iindex)"
                  ></i>
                </el-input>
                <el-button type="primary" @click="addOneOptionItem(sindex)"
                  >添加{{ sitem.name }}选项</el-button
                >
              </el-form-item>

              <el-table
                key="option"
                :data="formDefaultValue.spec_value"
                v-if="formDefaultValue.spec_value.length > 0"
              >
                <el-table-column label="SKU">
                  <template slot-scope="{ row }">
                    {{ row.title }}
                  </template>
                </el-table-column>
                <el-table-column label="销售价">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.price" />
                  </template>
                </el-table-column>
                <el-table-column label="原价">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.original_price" />
                  </template>
                </el-table-column>
                <el-table-column label="成本价">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.cost_price" />
                  </template>
                </el-table-column>
                <el-table-column label="库存">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.stock" />
                  </template>
                </el-table-column>
                <el-table-column label="货号">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.goodssn" />
                  </template>
                </el-table-column>
                <el-table-column label="佣金">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.commission" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="details">
            <Tinymce
              ref="editor"
              v-model="formDefaultValue.description.goods_content"
              :height="400"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submitGoodsForm"> 确认 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import store from "@/store";
export default {
  name: "List",
  components: { Tinymce },
  data() {
    return {
      tabList: [
        { label: "全部商品", key: "all" },
        { label: "已上架", key: "onsale" },
        { label: "已下架", key: "offsale" },
        { label: "待审核", key: "pending" },
        { label: "已拒绝", key: "refusal" },
        { label: "回收站", key: "recyclein" },
      ],
      activeName: "all",
      formTabActiveName: "base",
      goodsList: [],
      total: 0,
      listLoading: false,
      getInfoLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        page_filter: "all",
      },
      dialogStatus: "",
      textMap: {
        update: "编辑商品",
        create: "添加商品",
      },
      formDefaultValue: {
        id: undefined,
        categories: [], // 分类id集
        title: "", // 标题
        subtitle: "", // 副标题
        brand_id: "", // 品牌id
        dispatch_price: "0.00", // 运费
        images: [], // 图片
        status: "1", // 状态
        price: "", // 售价
        cost_price: "", // 原价
        original_price: "", // 成本价
        min_buy: "1", // 最小购买数量
        codes: "", // 商品编码
        weight: "", // 商品重量
        total: "", // 商品库存
        hasoption: 0, // 是否开启选项
        spec_item: [], // 规格
        spec_value: [], // 规格值
        description: { goods_content: "" }, // 商品详情
      }, // 表单默认值
      goodsImages: [], // 显示的图片

      goodCategory: [],
      goodsBrands: [],
      cascaderProps: {
        multiple: true,
        value: "id",
        label: "name",
        expandTrigger: "hover",
      }, // 联级选择器配置
      statusOptions: [
        { val: 1, text: "上架" },
        { val: 1, text: "下架" },
      ],
      dialogImageUrl: undefined, // 预览图片
      dialogImageVisible: false, // 预览图片
      dialogFormVisible: false, // 编辑添加弹窗是否显示
      rules: {
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      }, // 验证规则
      headers: {},
      uploadUrl: "",
    };
  },
  created() {
    this.uploadUrl = process.env.VUE_APP_BASE_API + "/shopadminapi/upload";
    this.headers["Authorization"] = "Bearer " + store.getters.token;
    // 获取商品列表
    this.getList();
  },
  methods: {
    // 获取商品列表
    getList() {
      let _this = this;
      this.listLoading = true;
      this.$ApiGoods
        .getList(_this.listQuery)
        .then((res) => {
          console.log("商品列表", res.data.list);
          if (res.code == 1) {
            _this.goodsList = res.data.list;
            _this.total = res.data.total;
          } else {
            _this.$message(res.msg);
          }

          _this.listLoading = false;
        })
        .catch((err) => {
          _this.listLoading = false;
          console.log(err);
        });
    },

    // 筛选商品列表
    handleFilter() {
      this.listQuery.page = 1; //请求页重置为1
      this.getList();
    },

    // 商品表单弹出处理
    handleShowGoodsForm(action = undefined, goods = {}) {
      this.dialogStatus = action;
      this.dialogFormVisible = true;
      this.getInfoLoading = true;
      this.$nextTick(() => {
        this.$refs["goodsFormRef"].clearValidate();
      });
      const _this = this;
      this.getCategories();
      if (action == "update" && goods.goods_id != undefined) {
        this.$ApiGoods
          .getInfo({ goods_id: goods.goods_id })
          .then((res) => {
            _this.formDefaultValue = res.data;
            console.log("分类", res.data.categories);

            // 处理分类
            let cates = [];
            res.data.categories.forEach((cate) => {
              cates.push([
                cate.pivot.level1_id,
                cate.pivot.level2_id,
                cate.pivot.category_id,
              ]);
            });
            _this.formDefaultValue.categories = cates;
            console.log("分类ids", _this.formDefaultValue.categories);

            this.getBrands(false);

            let imgs = [];
            res.data.images.forEach((item) => {
              imgs.push({ url: item.image });
            });
            _this.formDefaultValue.images = imgs;
            _this.goodsImages  = imgs
            _this.getInfoLoading = false;
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.getInfoLoading = false;
      }
    },

    // 关闭表单处理
    handleGoodsFormClose() {
      this.$refs.goodsFormRef.resetFields(); //重置表单值
      this.$refs.upload.clearFiles(); //清空表单图片列表
      this.formTabActiveName = "base"; // 把表单选项卡置为基本信息
    },

    // 获取品牌
    getBrands(clearSelected = true) {
      if (clearSelected) {
        // 清除已经选择的品牌
        this.formDefaultValue.brand_id = "";
      }
      let ids = [];
      this.formDefaultValue.categories.forEach((cids) => {
        // 处理,只用最小级分类id作为请求参数
        ids.push(cids[cids.length - 1]);
      });
      console.log("获取品牌传的分类id", ids);
      const _this = this;
      this.$ApiGoods
        .getBrands({ cids: ids })
        .then((res) => {
          console.log(res);
          if (res.code === 1) {
            _this.goodsBrands = res.data.list;
          } else {
            this.$message.error("获取品牌" + res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 获取分类
    getCategories() {
      const _this = this;
      this.$ApiGoods
        .getCategory()
        .then((res) => {
          console.log(res);
          if (res.code === 1) {
            _this.goodCategory = res.data;
          } else {
            this.$message.error("获取分类" + res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 页签切换处理
    handleClick(tab) {
      this.listQuery.page_filter = tab.name;
      this.handleFilter(); // 执行筛选
    },

    // 设置商品状态
    switchChange(row) {
      this.$ApiGoods
        .setStatus({ goods_ids: [row.goods_id], status: row.status })
        .then((res) => {
          this.$message({ message: res.msg, type: "success" });
        });
    },

    // 删除商品处理
    handleDeleteGoods(row) {
      this.$confirm("删除商品,", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$ApiGoods
            .deleteGoods({ goods_ids: [row.goods_id], is_delete: 1 })
            .then((res) => {
              if (res.code == 1) {
                this.getList();
                this.$message({
                  type: "success",
                  message: res.msg,
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 添加一个规格
    addOneOption() {
      this.$prompt("请输入规格名称", "", {
        inputPlaceholder: "请输入选项名称，如：颜色",
      }).then(({ value }) => {
        this.formDefaultValue.spec_item.push({ name: value, item: [] });
      });
    },

    // 添加一个规格选项
    addOneOptionItem(index) {
      let option = this.formDefaultValue.spec_item[index];
      this.$prompt("添加选项会重新组合，将会清除下方已经输入的价格等信息", "", {
        inputPlaceholder: "请输入" + option.name + "选项名称",
      }).then(({ value }) => {
        option.item.push({
          title: value,
          image: "",
        });
        this.buildSKU();
      });
    },

    // 删除规格
    deleteSpec(index) {
      let _this = this;
      this.$confirm("将清空以下价格等信息", "删除规格", {
        type: "warning",
      }).then(() => {
        _this.formDefaultValue.spec_item.splice(index, 1);
        _this.buildSKU();
      });
    },

    // 删除规格选项
    deleteSpecItem(sindex, iindex) {
      console.log("下摆哦", sindex, iindex);
      let _this = this;
      this.$confirm("将清空以下价格等信息", "删除选项", {
        type: "warning",
      }).then(() => {
        _this.formDefaultValue.spec_item[sindex].item.splice(iindex, 1);
        _this.buildSKU();
      });
    },

    // 规格选项组合
    buildSKU() {
      let options = this.formDefaultValue.spec_item;
      let arr = [];
      options.forEach((spec, index) => {
        arr[index] = [];
        spec.item.forEach((spu) => {
          arr[index].push(spu.title);
        });
      });
      this.formDefaultValue.spec_value = [];
      let skus = calcDescartes(arr);
      console.log(skus);
      skus.forEach((sku) => {
        let title = "";
        if (Array.isArray(sku)) {
          sku.forEach((val, inx) => {
            if (inx !== 0) {
              title += "-";
            }
            title += val;
          });
        } else {
          title = sku;
        }
        this.formDefaultValue.spec_value.push({
          title: title,
          price: "",
          original_price: "",
          cost_price: "",
          stock: "",
          goodssn: "",
          commission: "",
        });
      });
      console.log(this.formDefaultValue.spec_value);
    },

    /**
     * 提交表单
     */
    submitGoodsForm() {
      const _this = this;
      let action = _this.dialogStatus;
      this.$refs.goodsFormRef.validate((valid) => {
        if (valid) {
          _this.$ApiGoods[action](_this.formDefaultValue)
            .then((res) => {
              console.log(res);
              if (res.code === 1) {
                _this.$message.success("操作" + res.msg);
                _this.getList();
              } else {
                _this.$message.error("操作" + res.msg);
              }
              _this.dialogFormVisible = false;
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          _this.$message("操作失败");
          return false;
        }
      });
    },

    // 图片上传成功Hook
    uploadSuccessHook(response, file, fileList) {
      const url = response.data.src;
      console.log(url)
      console.log(this.goodsImages)
      this.formDefaultValue.images.push({ url: url });
    },

    // 删除上传的图片
    handleRemove(file, fileList) {
      this.formDefaultValue.images.forEach(function (item, index, arr) {
        if (item.url == file.url) {
          arr.splice(index, 1);
        }
      });
      console.log(this.formDefaultValue.images)
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
  },
};
function calcDescartes(array) {
  if (array.length < 2) return array[0] || [];

  return [].reduce.call(array, function (col, set) {
    var res = [];

    col.forEach(function (c) {
      set.forEach(function (s) {
        var t = [].concat(Array.isArray(c) ? c : [c]);
        t.push(s);
        res.push(t);
      });
    });

    return res;
  });
}
</script>

<style>
.spec-option {
  width: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.spec-option-item {
  width: 130px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.spec-option .el-input__inner,
.spec-option-item .el-input__inner {
  border: 1px solid #3ea1f1;
}
</style>
